package com.zhao;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
/**
 * Xml文件创建器
 * @author Zhao
 *
 */
public class XmlCreater {
	//xml头文件
	private final static String XML_HEAD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	private OutputStreamWriter osw;
	private StringBuffer sb;
	//控制格式 TAB 数量
	private int tabCount;
	

	
	public XmlCreater(File file){
		tabCount=0;
		sb = new StringBuffer();
		try {
			osw = new OutputStreamWriter(new FileOutputStream(file));
			osw.write(XML_HEAD);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//追加起始节点
	public void appendStartNode(String name){
		sb.append("\r\n");
		for (int i = 0; i < tabCount ; i++) {
			sb.append("\r\t");
		}
		tabCount++;
		sb.append("<"+name+">");
	}
	//追加结束节点
	public void appendEndNode(String name){
		sb.append("</"+name+">");
		sb.append("\r\n");
		tabCount--;
		for (int i = 0; i < tabCount-1 ; i++) {
			sb.append("\r\t");
		}
	}
	//追加数据
	public void appendData(String name){
		sb.append(name);
	}
	//提交
	public void commit(){
		try {
			osw.write(sb.toString());
			osw.flush();
			osw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public XmlCreater(String filePath){
		this(new File(filePath));
	}

	public static void main(String[] args) {
		XmlCreater xc = new XmlCreater(".Data.xml");
		xc.appendStartNode("Person");
		
			xc.appendStartNode("Name");
			xc.appendData("Zhao YueNing");
			xc.appendEndNode  ("Name");
			
			xc.appendStartNode("Age");
			xc.appendData("19");
			xc.appendEndNode("Age");
			
			xc.appendStartNode("Home");
			xc.appendData("ChangSha");
			xc.appendEndNode("Home");
			
		xc.appendEndNode("Person");
		
		xc.commit();
	}
}
